<?php

namespace App\B2BProject\Site;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class ArticleCategory extends Model
{
    protected $fillable = ['name', 'display_name'];

    protected $expectCategory = ['helper', 'rzxy', 'dbxx'];

    /**
     * 该分类下的所有文章
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function articles()
    {
        return $this->hasMany('App\B2BProject\Site\Article', 'category_id', 'id');
    }

    public function parent()
    {
        return $this->belongsTo('App\B2BProject\Site\ArticleCategory', 'parent_id', 'id');
    }

    public function children()
    {
        return $this->hasMany('App\B2BProject\Site\ArticleCategory', 'parent_id', 'id');
    }

    /**
     * @param $categoryName
     *
     * @return Article
     */
    public static function getArticleCollectionByCategoryName($categoryName)
    {
        $category = static::where('name', $categoryName)->firstOrFail();

        return $category->articles();
    }

    /**
     * @param $categoryName
     *
     * @return mixed
     */
    public static function getCategoryCollectionByCategoryName($categoryName)
    {
        $category = static::where('name', $categoryName)->firstOrFail();

        return $category->children();
    }

    /**
     * @param Builder $builder
     *
     * @return array
     */
    public function scopeCategoryFilter(Builder $builder)
    {
        $parents  = with(clone $builder)->whereIn('name', $this->expectCategory)->lists('id')->toArray() ?: [];
        $children = with(clone $builder)->whereIn('parent_id', $parents)->lists('id')->toArray() ?: [];

        return array_merge($parents, $children);
    }
}
